package org.pz.component;

import org.pz.anno.BeanTask;
import org.pz.task.BaseSchedulerTask;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来扫描所有的定时任务
 * */
@Component
public class ScheduleTaskCollections implements ApplicationContextAware {

    private final Map<String, BaseSchedulerTask> taskMap = new HashMap<>();

    public BaseSchedulerTask findTaskClassByValue(String value){
        BaseSchedulerTask bt;
        if((bt = taskMap.get(value)) == null){
            throw new RuntimeException("未匹配到合适的 task");
        }
        return bt;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanTaskMap = applicationContext.getBeansWithAnnotation(BeanTask.class);
        if(!beanTaskMap.isEmpty()){
            for( Map.Entry<String, Object> entry : beanTaskMap.entrySet()){
                if(entry.getValue() instanceof BaseSchedulerTask){
                    BeanTask annotation = AnnotationUtils.getAnnotation(entry.getValue().getClass(), BeanTask.class);
                    taskMap.put(annotation.value(), (BaseSchedulerTask) entry.getValue());
                }
            }
        }
    }
}
